package com.yuyou.tas.admin.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.yuyou.tas.admin.mapper.AuthRoleMapper;
import com.yuyou.tas.admin.mapper.AuthUserMapper;
import com.yuyou.tas.admin.mapper.AuthUserRoleRelationMapper;
import com.yuyou.tas.admin.mapper.AuthUserSectionMapper;
import com.yuyou.tas.admin.mapper.AuthUserSubjectMapper;
import com.yuyou.tas.admin.service.IAuthOrganService;
import com.yuyou.tas.admin.service.IAuthRoleService;
import com.yuyou.tas.admin.service.IAuthUserRoleRelationService;
import com.yuyou.tas.admin.service.IAuthUserSchoolService;
import com.yuyou.tas.admin.service.IAuthUserService;
import com.yuyou.tas.admin.vo.req.AuthSubjectSection;
import com.yuyou.tas.admin.vo.req.ReqAuthUserAdd;
import com.yuyou.tas.admin.vo.req.ReqAuthUserUpdate;
import com.yuyou.tas.admin.vo.req.ReqSysAuthUserAdd;
import com.yuyou.tas.admin.vo.req.ReqSysAuthUserUpdate;
import com.yuyou.tas.service.api.admin.dto.AuthUserDTO;
import com.yuyou.tas.service.api.admin.dto.AuthUserSectionDTO;
import com.yuyou.tas.service.api.admin.dto.AuthUserSubjectDTO;
import com.yuyou.tas.service.api.admin.dto.Section;
import com.yuyou.tas.service.api.admin.dto.SubjectSection;
import com.yuyou.tas.service.api.admin.dto.SycnUserUpdateObj;
import com.yuyou.tas.service.api.admin.dto.SysAuthUserDTO;
import com.yuyou.tas.service.api.admin.dto.TeacherDTO;
import com.yuyou.tas.service.api.admin.entity.AuthOrganization;
import com.yuyou.tas.service.api.admin.entity.AuthRole;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.entity.AuthUserRoleRelation;
import com.yuyou.tas.service.api.admin.entity.AuthUserSchool;
import com.yuyou.tas.service.api.admin.entity.AuthUserSection;
import com.yuyou.tas.service.api.admin.entity.AuthUserSubject;
import com.yuyou.tas.service.api.lesson.entity.BaseSection;
import com.yuyou.tas.service.api.lesson.entity.LessonClass;
import com.yuyou.tas.service.api.lesson.entity.LessonClassUserRel;
import com.yuyou.tas.service.api.lesson.service.BaseDataAPI;
import com.yuyou.tas.service.api.lesson.service.LessonClassAPI;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.config.SystemConfig;
import com.yuyou.tas.util.enums.admin.AuthRoleEnums;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.message.admin.AuthUserMess;
import com.yuyou.tas.util.tool.BeanUtils;
import com.yuyou.tas.util.tool.DateUtil;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.LogUtil;
import com.yuyou.tas.util.tool.PingYinUtil;
import com.yuyou.tas.util.tool.Sequence;

/**
 * Created by yujin.liu on 2018/1/19.
 */
@Service
public class AuthUserServiceImpl implements IAuthUserService{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
    @Autowired
    private AuthUserMapper authUserMapper;

    @Autowired
    private AuthUserSubjectMapper authUserSubjectMapper;

    @Autowired
    private AuthUserSectionMapper authUserSectionMapper;

    @Autowired
    private AuthRoleMapper authRoleMapper;

    @Autowired
    private BaseDataAPI baseDataAPI;

    @Autowired
    private AuthUserRoleRelationMapper authUserRoleRelationMapper;

    @Autowired
    private IAuthUserRoleRelationService authUserRoleRelationService;

    @Autowired
    private IAuthOrganService authOrganService;

    @Autowired
    private LessonClassAPI lessonClassAPI;
    
    @Autowired
    private IAuthRoleService authRoleService;
    
    @Autowired
    private IAuthUserService authUserService;
    
    @Autowired
    private AuthUserServiceAopImpl authUserServiceAopImpl;

    @Autowired
    private IAuthUserSchoolService authUserSchoolService;

    
    @Override
	public ResBoolSimpleInfo<String> addOrUpUser(AuthUser authUser,boolean isOIdSycn) throws Exception {	
    	
    	AuthUser sycnAuthUser=null;
    	if(isOIdSycn){
    		sycnAuthUser=authUserMapper.selectByOrgan7OId(authUser.getoId(), authUser.getAuthOrganizationId());
    	}   		
		if(authUser.getId()!=null&& !isOIdSycn){
			this.updateByPrimaryKeySelective(authUser);
		}else if(isOIdSycn&& sycnAuthUser !=null){
			authUser.setId(sycnAuthUser.getId());
			this.updateByPrimaryKeySelective(authUser);
		}else{	
			this.insert(authUser);	
		}	
		return ResBoolSimpleInfo.getSuccessInfo();
	}
    
	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> addOrUpUsers(List<AuthUser> list,boolean isOIdSycn) throws Exception {	
		for(AuthUser l: list){
			this.addOrUpUser(l,isOIdSycn);
		}		
		return ResBoolSimpleInfo.getSuccessInfo();
	}
    
	
    @Override
    public AuthUserDTO findAuthUser(Long id){
        // 查询年级数据
        Map<String, Object> condition = new HashMap<>();
        List<BaseSection> sectionName = baseDataAPI.findSectionName(condition);
        Map<Long, BaseSection> baseSectionMap = BeanUtils.toMap(sectionName, "id");

        AuthUserDTO authUserDTO = authUserMapper.selectUserById(id);
        List<AuthUserSectionDTO> authUserSectionDTOList = authUserSectionMapper.findSectionByAuthUserId(id);
        authUserDTO.setSubjectSectionList(this.getSubjectSection(authUserSectionDTOList, baseSectionMap));
        authUserDTO.setAuthRoleList(authRoleMapper.findAuthRoleByUserId(id));
        authUserDTO.setBaseSchoolIds(authUserSchoolService.findBaseSchoolIdByAuthUserId(id));

        return authUserDTO;
    }

    @Override
    public List<SubjectSection> getSubjectSection(List<AuthUserSectionDTO> authUserSectionList, Map<Long, BaseSection> baseSectionMap){
        List<SubjectSection> subjectSectionList = new ArrayList<>();
        if(null == authUserSectionList){
            return subjectSectionList;
        }
        for(AuthUserSectionDTO authUserSection : authUserSectionList){
            SubjectSection subjectSection = new SubjectSection();
            // 科目
            subjectSection.setSubjectId(authUserSection.getDataSubject());
            subjectSection.setSubjectName(authUserSection.getSubjectName());

            // 学段
            List<Section> sectionList = new ArrayList<>();
            String baseSectionIdStr = authUserSection.getBaseSectionId();
            if(StringUtils.isNotEmpty(baseSectionIdStr)){
                List<Long> baseSectionIds = Arrays.asList(baseSectionIdStr.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                for(Long  baseSectionId : baseSectionIds){
                    Section section = new Section();
                    section.setSectionId(baseSectionId);
                    section.setSectionName(baseSectionMap.get(baseSectionId).getName());
                    sectionList.add(section);
                }
            }

            subjectSection.setSectionList(sectionList);
            subjectSectionList.add(subjectSection);
        }
        return subjectSectionList;
    }


    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo insertAuthUser(ReqAuthUserAdd reqAuthUserAdd, LoginRedisObj loginObj){
        ResBoolSimpleInfo res = new ResBoolSimpleInfo();

        AuthOrganization authOrganization = authOrganService.selectByPrimaryKey(loginObj.getOrganizationId());
        int total = authUserMapper.countByOrganId(loginObj.getOrganizationId() , new ArrayList<Integer>(){
            {
                add(3);//个人合作
                add(2);//合作机构
            }
        });//获取该机构下已创建的用户数，排除机构管理员
        if(total >= authOrganization.getFreeAccount()){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_IS_ENOUGH);
            return res;
        }


        AuthUser authUser = new AuthUser();
        DefindBeanUtils.copyProperties(reqAuthUserAdd, authUser);
        authUser.setSpell(PingYinUtil.getFirstPYIndexStr(authUser.getUsername(), true));
        authUser.setAuthOrganizationId(loginObj.getOrganizationId());

        AuthUser authUserQuery = seleteUserByAcc7Organ(authUser.getAccount(), authUser.getAuthOrganizationId());
        if(null != authUserQuery){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_EXIST);
            return res;
        }

/*        // 校区权限:0:全部，1:部分
        if(!CollectionUtils.isEmpty(reqAuthUserAdd.getBaseSchoolIds())){
            authUser.setSchoolType(AuthUserEnums.schoolType.part.getValue());
        }else{
            authUser.setSchoolType(AuthUserEnums.schoolType.all.getValue());
        }*/

        authUser.setId(Sequence.getSequence().nextId());
        authUser.setStatus(AuthUserEnums.status.normal.getValue());
        authUser.setCreateTime(DateUtil.now());
        authUser.setUpdateTime(DateUtil.now());
        authUserMapper.insert(authUser);

        // 添加角色关系
        for(Long authRoleId : reqAuthUserAdd.getAuthRoleIds()){
            AuthUserRoleRelation authUserRoleRelation = new AuthUserRoleRelation();
            authUserRoleRelation.setId(Sequence.getSequence().nextId());
            authUserRoleRelation.setAuthUserId(authUser.getId());
            authUserRoleRelation.setAuthRoleId(authRoleId);
            authUserRoleRelation.setCreateTime(DateUtil.now());
            authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelation);
        }

        // 添加科目年级
        for(AuthSubjectSection authSubjectSection : reqAuthUserAdd.getAuthSubjectSectionList()){
            AuthUserSubject authUserSubject = new AuthUserSubject();
            authUserSubject.setId(Sequence.getSequence().nextId());
            authUserSubject.setAuthUser(authUser.getId());
            authUserSubject.setDataSubject(authSubjectSection.getSubjectId());
            authUserSubject.setCreateTime(DateUtil.now());
            authUserSubjectMapper.insert(authUserSubject);

            AuthUserSection authUserSection = new AuthUserSection();
            authUserSection.setId(Sequence.getSequence().nextId());
            authUserSection.setAuthUser(authUser.getId());
            authUserSection.setBaseSectionId(authSubjectSection.getBaseSectionIds());
            authUserSection.setDataSubject(authSubjectSection.getSubjectId());
            authUserSection.setCreateTime(DateUtil.now());
            authUserSectionMapper.insert(authUserSection);
        }

        // 添加校区权限
        if(!CollectionUtils.isEmpty(reqAuthUserAdd.getBaseSchoolIds())){
            for(Long baseSchoolId : reqAuthUserAdd.getBaseSchoolIds()){
                AuthUserSchool authUserSchool = new AuthUserSchool();
                authUserSchool.setId(Sequence.getSequence().nextId());
                authUserSchool.setAuthOrganizationId(loginObj.getOrganizationId());
                authUserSchool.setAuthUser(authUser.getId());
                authUserSchool.setBaseSchoolId(baseSchoolId);
                authUserSchool.setCreateTime(DateUtil.now());

                authUserSchoolService.insert(authUserSchool);
            }
        }

        return ResBoolSimpleInfo.getSuccessInfo();
    }

    @Override
    public ResBoolSimpleInfo updateSysAuthUser(ReqSysAuthUserUpdate sysAuthUserUpdate, LoginRedisObj loginObj) {
        AuthUser authUser = new AuthUser();
        DefindBeanUtils.copyProperties(sysAuthUserUpdate, authUser);
        authUser.setSpell(PingYinUtil.getFirstPYIndexStr(authUser.getUsername(), true));

        //如果系统管理员，设置机构id,前端还是传机构id出现bug
        if(null == authUser.getAuthOrganizationId()){
            authUser.setAuthOrganizationId(loginObj.getOrganizationId());
        }
        
        ////如果系统管理员，设置系统机构id
        AuthRole ruthRole=authRoleService.selectByPrimaryKey(String.valueOf(sysAuthUserUpdate.getAuthRoleId()));
        if(ruthRole.getRoleType().intValue()==AuthRoleEnums.roleType.system.getValue()){
        	authUser.setAuthOrganizationId(SystemConfig.SYS_ORGAN_ID);
        }
        
        
        ResBoolSimpleInfo res = new ResBoolSimpleInfo();
        AuthUser authUserQuery = selectByPrimaryKey(authUser.getId());
        if(null == authUserQuery){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_NOT_EXIST);
            return res;
        }

        // 检验同机构同账号是否存在
        AuthUser authUserExist = seleteUserByAcc7Organ(authUser.getAccount(), authUser.getAuthOrganizationId());
        if(null != authUserExist && !authUserExist.getId().equals(authUser.getId())){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_EXIST);
            return res;
        }

        authUser.setUpdateTime(DateUtil.now());
        authUserMapper.updateByPrimaryKeySelective(authUser);

        // 添加角色关系
        authUserRoleRelationService.deleteByUserId(authUser.getId());
        AuthUserRoleRelation authUserRoleRelation = new AuthUserRoleRelation();
        authUserRoleRelation.setId(Sequence.getSequence().nextId());
        authUserRoleRelation.setAuthUserId(authUser.getId());
        authUserRoleRelation.setAuthRoleId(sysAuthUserUpdate.getAuthRoleId());
        authUserRoleRelation.setCreateTime(DateUtil.now());
        authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelation);

        for(Long authRoleId : sysAuthUserUpdate.getAddAuthRoleIds()){
            AuthUserRoleRelation authUserRoleRelationAdd = new AuthUserRoleRelation();
            authUserRoleRelationAdd.setId(Sequence.getSequence().nextId());
            authUserRoleRelationAdd.setAuthUserId(authUser.getId());
            authUserRoleRelationAdd.setAuthRoleId(authRoleId);
            authUserRoleRelationAdd.setCreateTime(DateUtil.now());
            authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelationAdd);
        }
        return ResBoolSimpleInfo.getSuccessInfo();
    }

    @Override
    public ResBoolSimpleInfo updateStatus(Long id, Integer status) {
        AuthUser authUser = new AuthUser();
        authUser.setId(id);
        authUser.setStatus(status);
        authUserMapper.updateByPrimaryKeySelective(authUser);

        return ResBoolSimpleInfo.getSuccessInfo();
    }


    @Override
    public ResBoolSimpleInfo<String> updateAuthUser(ReqAuthUserUpdate reqAuthUserUpdate, LoginRedisObj loginObj){
        AuthUser authUser = new AuthUser();
        DefindBeanUtils.copyProperties(reqAuthUserUpdate, authUser);

        ResBoolSimpleInfo<String> res = new ResBoolSimpleInfo<String>();
        AuthUser authUserQuery = selectByPrimaryKey(authUser.getId());
        if(null == authUserQuery){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_NOT_EXIST);
            return res;
        }


        // 检验同机构同账号是否存在
        AuthUser authUserExist = seleteUserByAcc7Organ(authUser.getAccount(), loginObj.getOrganizationId());
        if(null != authUserExist && !authUserExist.getId().equals(authUser.getId())){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_EXIST);
            return res;
        }

/*        // 校区权限
        if(!CollectionUtils.isEmpty(reqAuthUserUpdate.getBaseSchoolIds())){
            authUser.setSchoolType(AuthUserEnums.schoolType.part.getValue());
        }else{
            authUser.setSchoolType(AuthUserEnums.schoolType.all.getValue());
        }*/

        /*List<LessonClassUserRel> lessonClassUserRelList = lessonClassAPI.findByUserId(reqAuthUserUpdate.getId());

        if(null != lessonClassUserRelList && lessonClassUserRelList.size() > 0){
        	String classNamesStr=getClassNamesStr(lessonClassUserRelList);

            if(reqAuthUserUpdate.getWorkStatus() != authUserQuery.getWorkStatus()){
                res.setSuccess(false);
                res.setMessage("人员状态不能更改，因为" + AuthUserMess.USER_CLASS_REL + classNamesStr + ",请先解除引用关系");
                return res;
            }

            if(reqAuthUserUpdate.getType()!= authUserQuery.getType()){
                res.setSuccess(false);
                res.setMessage("人员类型不能更改，因为" + AuthUserMess.USER_CLASS_REL + classNamesStr + ",请先解除引用关系");
                return res;
            }
            
            ResBoolSimpleInfo<String> resVal=validateUserSubAndSec(classNamesStr,reqAuthUserUpdate.getAuthSubjectSectionList(),reqAuthUserUpdate.getId());
            if(!resVal.isSuccess()){
                return resVal;
            }

        }*/


        authUser.setUpdateTime(DateUtil.now());
        authUserMapper.updateByPrimaryKeySelective(authUser);

        // 更新角色关系，先删除再插入
        authUserRoleRelationService.deleteByUserId(authUser.getId());
        for(Long authRoleId : reqAuthUserUpdate.getAuthRoleIds()){
            AuthUserRoleRelation authUserRoleRelation = new AuthUserRoleRelation();
            authUserRoleRelation.setId(Sequence.getSequence().nextId());
            authUserRoleRelation.setAuthUserId(authUser.getId());
            authUserRoleRelation.setAuthRoleId(authRoleId);
            authUserRoleRelation.setCreateTime(DateUtil.now());
            authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelation);
        }

        // 删除年级科目，再插入
        authUserSubjectMapper.deleteByAuthUserId(authUser.getId());
        authUserSectionMapper.deleteByAuthUserId(authUser.getId());
        // 添加科目年级
        for(AuthSubjectSection authSubjectSection : reqAuthUserUpdate.getAuthSubjectSectionList()){
            AuthUserSubject authUserSubject = new AuthUserSubject();
            authUserSubject.setId(Sequence.getSequence().nextId());
            authUserSubject.setAuthUser(authUser.getId());
            authUserSubject.setDataSubject(authSubjectSection.getSubjectId());
            authUserSubject.setCreateTime(DateUtil.now());
            authUserSubjectMapper.insert(authUserSubject);

            AuthUserSection authUserSection = new AuthUserSection();
            authUserSection.setId(Sequence.getSequence().nextId());
            authUserSection.setAuthUser(authUser.getId());
            authUserSection.setBaseSectionId(authSubjectSection.getBaseSectionIds());
            authUserSection.setDataSubject(authSubjectSection.getSubjectId());
            authUserSection.setCreateTime(DateUtil.now());
            authUserSectionMapper.insert(authUserSection);
        }

        // 添加校区权限
        authUserSchoolService.deleteByAuthUserId(authUser.getId()); // 先删再增
        if(AuthUserEnums.schoolType.part.getValue() == reqAuthUserUpdate.getSchoolType() && !CollectionUtils.isEmpty(reqAuthUserUpdate.getBaseSchoolIds())){
            for(Long baseSchoolId : reqAuthUserUpdate.getBaseSchoolIds()){
                AuthUserSchool authUserSchool = new AuthUserSchool();
                authUserSchool.setId(Sequence.getSequence().nextId());
                authUserSchool.setAuthOrganizationId(loginObj.getOrganizationId());
                authUserSchool.setAuthUser(authUser.getId());
                authUserSchool.setBaseSchoolId(baseSchoolId);
                authUserSchool.setCreateTime(DateUtil.now());

                authUserSchoolService.insert(authUserSchool);
            }
        }
        return ResBoolSimpleInfo.getSuccessInfo();
    }
    @Override
    public String getClassNamesStr(List<LessonClassUserRel> lessonClassUserRelList){
        List<Long> lessonClassIdList = BeanUtils.toList(lessonClassUserRelList, "lessonClassId");
        List<Long> lessonClassIds = lessonClassIdList.stream().distinct().collect(Collectors.toList());
        List<LessonClass> lessonClassList = lessonClassAPI.findLessonClassByClassIds(lessonClassIds);

        final List<String> repeatsList = new ArrayList<>();
        lessonClassList.stream().forEach(lc -> repeatsList.add(lc.getName()));
        String classNamesStr = String.join(",",repeatsList);
        return classNamesStr;
    }

    
	@Override
	public ResBoolSimpleInfo<String> validateUserSubAndSec(String classNamesStr,List<AuthSubjectSection> ass,Long userId){
		ResBoolSimpleInfo<String> res = new ResBoolSimpleInfo<String>();
		
	    // 校验科目年级
	    List<AuthSubjectSection> authSubjectSectionList = ass;
	    List<Long> subjectIds = BeanUtils.toList(authSubjectSectionList, "subjectId");
	    List<AuthUserSubjectDTO> authUserSubjectList = authUserSubjectMapper.findSubjectByAuthUserId(userId);
	    List<Long> dataSubjects = BeanUtils.toList(authUserSubjectList, "dataSubject");
	    dataSubjects.removeAll(subjectIds);
	    if(null != dataSubjects && dataSubjects.size() > 0){
	        res.setSuccess(false);
	        res.setMessage("科目不能减少，因为" + AuthUserMess.USER_CLASS_REL + classNamesStr + ",请先解除引用关系");
	        return res;
	    }
	
	    for(AuthSubjectSection authSubjectSection : authSubjectSectionList){
	        String baseSectionIds = authSubjectSection.getBaseSectionIds();
	        List<Long> baseSectionIdList = Arrays.asList(baseSectionIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
	
	        AuthUserSection authUserSection = authUserSectionMapper.findSectionByUserIdSubjectId(userId, authSubjectSection.getSubjectId());
	        List<Long> sectionIdList = new ArrayList<>();
	        if(null != authUserSection){
	            sectionIdList = Arrays.asList(authUserSection.getBaseSectionId().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
	            sectionIdList.removeAll(baseSectionIdList);
	        }
	        if(null != sectionIdList && sectionIdList.size() > 0){
	            res.setSuccess(false);
	            res.setMessage("年级不能减少，因为" + AuthUserMess.USER_CLASS_REL + classNamesStr + ",请先解除引用关系");
	            return res;
	        }
	    }
		
	    res.setSuccess(true);
		return res;
	}
    
    
    
    @Override
    public int updateByPrimaryKeySelective(AuthUser authUser) {
        authUser.setUpdateTime(DateUtil.now());
        return authUserMapper.updateByPrimaryKeySelective(authUser);
    }
    @Override
    public int insert(AuthUser record){
    	record.setId(Sequence.getSequence().nextId());
    	record.setCreateTime(new Date());
    	return authUserMapper.insert(record);
    }
    
    @Override
    public int deleteAuthUserById(Long id) {
        return authUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int findAuthUserPageCount(Pagination<AuthUserDTO> p) {
        return authUserMapper.findAuthUserPageCount(p);
    }

    @Override
    public List<AuthUserDTO> findAuthUserPageList(Pagination<AuthUserDTO> p) {
        List<AuthUserDTO> authUserPageList = authUserMapper.findAuthUserPageList(p);
        for(AuthUserDTO authUserDTO : authUserPageList){
            authUserDTO.setAuthRoleList(authRoleMapper.findAuthRoleByUserId(authUserDTO.getId()));
        }
        return authUserPageList;
    }

    @Override
    public ResBoolSimpleInfo insertSysAuthUser(ReqSysAuthUserAdd sysAuthUserAdd, LoginRedisObj loginObj) {
        AuthUser authUser = new AuthUser();
        DefindBeanUtils.copyProperties(sysAuthUserAdd, authUser);

        //如果系统管理员，设置机构id
        if(null == authUser.getAuthOrganizationId()){
            authUser.setAuthOrganizationId(loginObj.getOrganizationId());
        }

        ResBoolSimpleInfo res = new ResBoolSimpleInfo();
        AuthUser authUserQuery = seleteUserByAcc7Organ(authUser.getAccount(), authUser.getAuthOrganizationId());
        if(null != authUserQuery){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_EXIST);
            return res;
        }

        authUser.setId(Sequence.getSequence().nextId());
        authUser.setStatus(AuthUserEnums.status.normal.getValue());
        authUser.setSchoolType(AuthUserEnums.schoolType.all.getValue());
        authUser.setCreateTime(DateUtil.now());
        authUser.setUpdateTime(DateUtil.now());
        authUserMapper.insert(authUser);

        // 添加角色关系
        AuthUserRoleRelation authUserRoleRelation = new AuthUserRoleRelation();
        authUserRoleRelation.setId(Sequence.getSequence().nextId());
        authUserRoleRelation.setAuthUserId(authUser.getId());
        authUserRoleRelation.setAuthRoleId(sysAuthUserAdd.getAuthRoleId());
        authUserRoleRelation.setCreateTime(DateUtil.now());
        authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelation);

        for(Long authRoleId : sysAuthUserAdd.getAddAuthRoleIds()){
            AuthUserRoleRelation authUserRoleRelationAdd = new AuthUserRoleRelation();
            authUserRoleRelationAdd.setId(Sequence.getSequence().nextId());
            authUserRoleRelationAdd.setAuthUserId(authUser.getId());
            authUserRoleRelationAdd.setAuthRoleId(authRoleId);
            authUserRoleRelationAdd.setCreateTime(DateUtil.now());
            authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelationAdd);

        }


        return ResBoolSimpleInfo.getSuccessInfo();
    }

    @Override
    public int findSysAuthUserPageCount(Pagination<SysAuthUserDTO> p) {
        return authUserMapper.findSysAuthUserPageCount(p);
    }

    @Override
    public List<SysAuthUserDTO> findSysAuthUserPageList(Pagination<SysAuthUserDTO> p) {
        List<SysAuthUserDTO> sysAuthUserPageList = authUserMapper.findSysAuthUserPageList(p);

        return sysAuthUserPageList;
    }

    @Override
	public AuthUser seleteUserByAcc7Organ(String account,Long authOrganizationId) {
		return authUserMapper.seleteUserByAcc7Organ(account,authOrganizationId);
	}


	@Override
	public AuthUser selectBaseByPrimaryKey(Long id) {
		return authUserMapper.selectBaseByPrimaryKey(id);
	}


	@Override
	public AuthUser selectByPrimaryKey(Long id) {
		return authUserMapper.selectByPrimaryKey(id);
	}
	
	
	@Override
	public ResBoolSimpleInfo<String> sycnUserByOId(List<SycnUserUpdateObj> list){					
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		StringBuilder sb=new StringBuilder();		
		for(SycnUserUpdateObj sycnUserUpdateObj:list){			
			try{
				authUserServiceAopImpl.sycnUserByOId(sycnUserUpdateObj);
			}catch(Exception e){
				LogUtil.error(logger, "同步用户失败:", e);
				sb.append("同步用户失败:"+e.getMessage()+"|");
			}
		}	
		res.setSuccess(StringUtils.isEmpty(sb.toString()));
		res.setMessage(sb.toString());
		return res;
	}

	@Override
	public AuthUser selectByOrgan7OId(Long oId, Long authOrganizationId) {
		return authUserMapper.selectByOrgan7OId(oId, authOrganizationId);
	}

    @Override
    public List<TeacherDTO> findTeacherList(Long dataSubject, Long baseSectionId, String keyword, Long organizationId, Long lessonClassId, Integer type) {
        List<TeacherDTO> teacherList = authUserMapper.findTeacherList(dataSubject, keyword, organizationId, lessonClassId, type);
        List<Long> teacherIds = BeanUtils.toList(teacherList, "id");

        Map<Long, List<AuthUserSectionDTO>> authUserSectionGroup = new HashMap<>();
        if(!CollectionUtils.isEmpty(teacherIds)){
            List<AuthUserSectionDTO> authUserSectionDTOList = authUserSectionMapper.findSectionByAuthUserIds(teacherIds);
            authUserSectionGroup = BeanUtils.toGroup(authUserSectionDTOList, "authUser");
        }

        // 查询年级数据
        Map<String, Object> condition = new HashMap<>();
        List<BaseSection> sectionName = baseDataAPI.findSectionName(condition);
        Map<Long, BaseSection> baseSectionMap = BeanUtils.toMap(sectionName, "id");


        Iterator<TeacherDTO> it = teacherList.iterator();

        // 批量查询 需要
        List<AuthUserSection> authUserSectionList = new ArrayList<>();
        Map<Long, AuthUserSection> authUserMap = new HashMap<>();
        if(null != dataSubject){
            authUserSectionList = authUserSectionMapper.findSectionBySubjectId(dataSubject);
            authUserMap = BeanUtils.toMap(authUserSectionList, "authUser");
        }

        while(it.hasNext()){
            TeacherDTO teacher = it.next();
            if(null != baseSectionId){
                AuthUserSection authUserSection = authUserMap.get(teacher.getId());
                List<Long> baseSectionIdList = Arrays.asList(authUserSection.getBaseSectionId().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                if(!baseSectionIdList.contains(baseSectionId)){
                    it.remove();
                    continue;
                }
            }
            List<SubjectSection> subjectSection = getSubjectSection(authUserSectionGroup.get(teacher.getId()), baseSectionMap);
            teacher.setSubjectSectionList(subjectSection);
        }

        return teacherList;
    }


	@Override
	public AuthUser findUserByAcc7UserId(String userId, String account) {

		// TODO Auto-generated method stub
		return null;
	}


}
